package top.tanyajun.exquicker.dao;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import top.tanyajun.exquicker.pojo.StudentBo;

import java.util.List;

/**
 *
 * @author 谭亚军 at 2022/5/3 18:16
 */
@Component
@Slf4j
public class StudentDao {
    private final StudentMock studentMock = new StudentMock();

    /**
     * 查询全部学生
     * @return 学生列表
     */
    public List<StudentBo> getAllStudents() {
        return studentMock.mockStudentList(1,studentMock.getTotalSize());
    }

    /**
     * 查询指定范围的学生
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 学生列表
     */
    public List<StudentBo> getStatudentWithPage(Integer pageNum, Integer pageSize) {
        Assert.isTrue(pageNum != null && pageSize != null,"pageNum or pageSize is null");
        Assert.isTrue(pageNum > 0 && pageSize > 0,"pageNum or pageSize is less than 0");
        if (pageSize > studentMock.getDataMaxSize()) {
            log.warn("pageSize is too large, set to {}", studentMock.getDataMaxSize());
        }
        return studentMock.mockStudentList(pageNum, Math.min(studentMock.getDataMaxSize(), pageSize));
    }

    /**
     * 查询学生总数
     * @return 学生总数
     */
    public Integer getStudentTotal() {
        return studentMock.getTotalSize();
    }


    private static class StudentMock{
        /**
         * 分页数据量最大值
         */
        private final static Integer DATA_MAX_SIZE = 2<<19;
        /**
         * 模拟数据库总数据量
         */
        private final static Integer TOTAL_SIZE = 3000000;

        List<StudentBo> mockStudentList(Integer pageNum, Integer pageSize) {
            List<StudentBo> students = Lists.newArrayList();
            long start = System.currentTimeMillis();
            for (int i = (pageNum-1)*pageSize; i < Math.min(pageNum*pageSize, TOTAL_SIZE); i++) {
                students.add(new StudentBo("张三" + i,(int)(Math.random()*20+10),"北京市朝阳区",System.currentTimeMillis()+"@qq.com", "1008611", String.valueOf(System.currentTimeMillis()), "计算机系",(int)(Math.random()*5+2018)+"级",(int)(Math.random()*6+1)+"班"));
            }
            log.info("生成数据耗时：{}ms", System.currentTimeMillis() - start);
            return students;
        }

        Integer getTotalSize() {
            return TOTAL_SIZE;
        }

        Integer getDataMaxSize() {
            return DATA_MAX_SIZE;
        }
    }
}
